package com.zyz.I_多线程.线程安全问题.同步方法;

/**
 * @author: vick
 * @Date: 2025/3/22
 * @Description:
 * @version: 1.0
 */
public class BuyTicket implements Runnable {
    private static int ticket = 10;
    @Override
    public void run() {
        while (ticket > 0) {
            saleTicket();
        }
    }

    //TODO 锁的是  BuyTicket类的Class对象，而一个类的Class对象在内存中肯定只有一个
    public synchronized static void saleTicket() {
        //不加条件，相当于条件判断没有进入锁管控，线程安全问题就没有解决
        if (ticket > 0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "卖出了一张票，票号" + ticket--);
        }
    }
}
